package com.yanqu.road.server.manger.activity.auto.send;

import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UnionActivityConditionData;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.player.UserHistoryAttribute;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.logic.bussiness.player.UserActivityBussiness;
import com.yanqu.road.logic.bussiness.player.UserHistoryAttributeBussiness;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.AutoSendRewardProto;
import com.yanqu.road.pb.crossunion.activity.CrossUnionActivityRankDataProto;
import com.yanqu.road.pb.rank.YRankProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.PlayerModule;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.activity.commonteam.CommonTeamMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.manger.union.UnionActivityMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class BaseAutoSendActivity {

    private static Logger logger = LogManager.getLogger(BaseAutoSendActivity.class.getName());

    protected ActivityInfo activityInfo;

    protected Map<Integer, List<ActivityConditionInfo>> conditionInfoMap;


    public BaseAutoSendActivity(ActivityInfo activityInfo) {
        this.activityInfo = activityInfo;
        conditionInfoMap = getActivityConditionInfo();
    }

    public static Logger getLogger() {
        return logger;
    }

    /**
     * 发送本服个人排行奖励
     */
    public abstract void sendLocalUserRankReward();

    /**
     * 发送本服商会排行奖励
     */
    public abstract void sendLocalUnionRankReward();

    /**
     * 通知跨服返回跨服个人榜单
     */
    public void noticeCrossUserRank() {
        AutoSendRewardProto.NoticeCrossUserRankMsg.Builder msg = AutoSendRewardProto.NoticeCrossUserRankMsg.newBuilder();
        msg.setActivityId(activityInfo.getActivityId());
        msg.setActivityType(activityInfo.getType());
        msg.setChildType(activityInfo.getChildType());
        YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_AUTO_SEND_USER_RANK_LIST, msg);
        GamePlayerMgr.sendPacket(0, message);
    }

    /**
     * 发送跨服个人排行奖励
     *
     * @param dataList
     */
    public void sendCrossUserRankReward(List<AutoSendRewardProto.UserRankMsg> dataList) {
        if (dataList.size() <= 0) {
            AutoSendActivity.getLogger().info("activity userRank data size is 0, activityId:{}, activityName:{}", activityInfo.getActivityId(), activityInfo.getActivityName());
        } else {
            Map<Integer, List<AutoSendRewardProto.UserRankMsg>> userRankMsgMap = new HashMap<>();
            for (AutoSendRewardProto.UserRankMsg msg : dataList) {

                int conditionType = msg.getConditionType();
                long userId = msg.getUserId();
                UserInfo userInfo = UserMgr.getUserInfo(userId);
                if (userInfo != null) {
                    if (!userRankMsgMap.containsKey(conditionType)) {
                        userRankMsgMap.put(conditionType, new ArrayList<>());
                    }
                    List<AutoSendRewardProto.UserRankMsg> list = userRankMsgMap.get(conditionType);
                    list.add(msg);
                }
            }
            for (Map.Entry<Integer, List<AutoSendRewardProto.UserRankMsg>> entry : userRankMsgMap.entrySet()) {
                Integer conditionType = entry.getKey();
                Map<Long, UserActivityConditionData> conditionDataMap = getUserActivityRankConditionData(activityInfo.getActivityId(), conditionType);
                List<AutoSendRewardProto.UserRankMsg> rankMsgList = entry.getValue();
                for (AutoSendRewardProto.UserRankMsg msg : rankMsgList) {
                    long userId = msg.getUserId();
                    UserActivityConditionData data = conditionDataMap.get(userId);
                    if (data == null) {
                        AutoSendActivity.getLogger().error("userActivityRankCondition is null, activityId:{}, userId:{}", activityInfo.getActivityId(), userId);
                        continue;
                    }
                    if (data.isGetReward()) {
                        continue;
                    }
                    data.setGetReward(true);
                    int rank = msg.getRank();
                    ActivityConditionInfo conditionInfo = getUserRankCondition(conditionType, rank);
                    if (conditionInfo != null && updateConditionData(data)) {
                        String rewardStr = conditionInfo.getRewardStr();
                        AutoSendActivity.getLogger().info("autoSend userReward, user: {}, activity: {},conditionType: {}, rank: {}, reward: {}", userId, activityInfo.getActivityId(), conditionType, rank, rewardStr);
                        sendMailReward(userId, rewardStr);

                        if (activityInfo.getType() == eActivityType.CrossRankActivity.getValue() && rank > 0 && rank < 4 &&
                                (conditionInfo.getType() == eGamePlayerEventType.AbilityRiseRank.getValue() || conditionInfo.getType() == eGamePlayerEventType.IntimacyRiseRank.getValue())) {//前三
                            GamePlayer player = GamePlayerMgr.getOnlinePlayer(msg.getUserId());
                            if (null != player) {
                                UserHistoryAttribute userHistoryAttribute = player.getModule(PlayerModule.class).getUserHistoryAttribute();
                                userHistoryAttribute.addCrossRankActivityTopThreeTotalTimes(activityInfo.getChildType());
                                player.notifyListener(eGamePlayerEventType.RankActivityTopThreeTotalTimes.getValue(), userHistoryAttribute);
                            } else {
                                UserHistoryAttribute attribute = UserHistoryAttributeBussiness.getUserHistoryAttribute(msg.getUserId());
                                if (attribute != null) {
                                    attribute.addCrossRankActivityTopThreeTotalTimes(activityInfo.getChildType());
                                    UserHistoryAttributeBussiness.updateUserHistoryAttribute(attribute);
                                }
                            }
                        }
                    }
                }
            }
        }
        AutoSendActivity.changeSendState(activityInfo.getActivityId(), 1, 1);
    }

    protected abstract boolean updateConditionData(UserActivityConditionData data);

    /**
     * 通知跨服返回跨服商会榜单
     */
    public void noticeCrossUnionRank() {
        AutoSendRewardProto.NoticeCrossUserRankMsg.Builder msg = AutoSendRewardProto.NoticeCrossUserRankMsg.newBuilder();
        msg.setActivityId(activityInfo.getActivityId());
        msg.setActivityType(activityInfo.getType());
        msg.setChildType(activityInfo.getChildType());
        YanQuMessage message = YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_AUTO_SEND_UNION_RANK_LIST, msg);
        GamePlayerMgr.sendPacket(0, message);
    }

    /**
     * 通知跨服，补发队伍奖励
     */
    public void noticeCrossTeamRank() {
        //判断是否在活动有接入通用组队
        boolean isCommonTeam = CommonTeamMgr.checkActivityType(activityInfo.getType());
        if (!isCommonTeam) {
            return;
        }
        Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
        //判断活动是分组活动，还是非分组活动
        if (UnionActivityGroupHelper.needGroup(activityInfo)) {
            if (groupMap == null || groupMap.isEmpty()) {
                logger.info("通用组队奖励补发-获取商会分组失败：{}", activityInfo.getActivityId());
                return;
            }
            //分组活动
            for (int groupId : groupMap.keySet()) {
                AutoSendRewardProto.NoticeCrossUserRankMsg.Builder msg = AutoSendRewardProto.NoticeCrossUserRankMsg.newBuilder();
                msg.setActivityId(activityInfo.getActivityId());
                msg.setActivityType(activityInfo.getType());
                msg.setChildType(activityInfo.getChildType());
                GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_AUTO_SEND_COMMON_TEAM_RANK_LIST, msg, 0, activityInfo.getActivityId(), groupId);
            }
        } else {
            //非分组活动
            AutoSendRewardProto.NoticeCrossUserRankMsg.Builder msg = AutoSendRewardProto.NoticeCrossUserRankMsg.newBuilder();
            msg.setActivityId(activityInfo.getActivityId());
            msg.setActivityType(activityInfo.getType());
            msg.setChildType(activityInfo.getChildType());
            GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_AUTO_SEND_COMMON_TEAM_RANK_LIST, msg, 0, activityInfo.getActivityId(), 0);
        }
    }

    /**
     * 通知跨服返回跨服商会榜单
     */
    public void noticeCrossUnionGroupRank() {
        if (!UnionActivityGroupHelper.isGroupActivityType(activityInfo.getType())) {
            throw new RuntimeException("看下是不是调用错方法了");
        }
        Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
        if (groupMap != null) {
            for (Map.Entry<Integer, UnionActivityGroup> groupEntry : groupMap.entrySet()) {
                UnionActivityGroup activityGroup = groupEntry.getValue();
                if(activityGroup.getServerSet().contains(GameServer.getInstance().getServerId())){
                    AutoSendRewardProto.NoticeCrossUserRankMsg.Builder msg = AutoSendRewardProto.NoticeCrossUserRankMsg.newBuilder();
                    msg.setActivityId(activityInfo.getActivityId());
                    msg.setActivityType(activityInfo.getType());
                    msg.setChildType(activityInfo.getChildType());
                    GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_AUTO_SEND_UNION_RANK_LIST_FOR_UNION_GROUP, msg, 0, activityGroup.getActivityId(), activityGroup.getGroupId());
                }
            }
        }
    }

    /**
     * 通知跨服返回跨服商会榜单
     */
    public void noticeCrossUserGroupRank() {
        if (!UnionActivityGroupHelper.isGroupActivityType(activityInfo.getType())) {
            throw new RuntimeException("看下是不是调用错方法了");
        }
        Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
        if (groupMap != null) {
            for (Map.Entry<Integer, UnionActivityGroup> groupEntry : groupMap.entrySet()) {
                UnionActivityGroup activityGroup = groupEntry.getValue();
                if (activityGroup.getServerSet().contains(GameServer.getInstance().getServerId())) {
                    AutoSendRewardProto.NoticeCrossUserRankMsg.Builder msg = AutoSendRewardProto.NoticeCrossUserRankMsg.newBuilder();
                    msg.setActivityId(activityInfo.getActivityId());
                    msg.setActivityType(activityInfo.getType());
                    msg.setChildType(activityInfo.getChildType());
                    GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_AUTO_SEND_USER_RANK_LIST_FOR_UNION_GROUP, msg, 0, activityGroup.getActivityId(), activityGroup.getGroupId());
                }
            }
        }
    }

    /**
     * 发送跨服商会排行奖励
     */
    public void sendCrossUnionRankReward(List<AutoSendRewardProto.UnionRankMsg> dataList) {
       if (dataList.size() <= 0) {
            AutoSendActivity.getLogger().info("activity unionRank data size is 0, activityId:{}, activityName:{}", activityInfo.getActivityId(), activityInfo.getActivityName());
        } else {
            Map<Integer, List<AutoSendRewardProto.UnionRankMsg>> userRankMsgMap = new HashMap<>();
            for (AutoSendRewardProto.UnionRankMsg msg : dataList) {

                int conditionType = msg.getConditionType();
                String unionId = msg.getUnionId();
                UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionId);
                if (unionInfo != null) {
                    if (!userRankMsgMap.containsKey(conditionType)) {
                        userRankMsgMap.put(conditionType, new ArrayList<>());
                    }
                    List<AutoSendRewardProto.UnionRankMsg> list = userRankMsgMap.get(conditionType);
                    list.add(msg);
                }
            }
            for (Map.Entry<Integer, List<AutoSendRewardProto.UnionRankMsg>> entry : userRankMsgMap.entrySet()) {
                Integer conditionType = entry.getKey();
                Map<Long, UserActivityConditionData> conditionDataMap = getUserActivityRankConditionData(activityInfo.getActivityId(), conditionType);
                List<AutoSendRewardProto.UnionRankMsg> rankMsgList = entry.getValue();
                for (AutoSendRewardProto.UnionRankMsg msg : rankMsgList) {
                    for (UserActivityConditionData data : conditionDataMap.values()) {
                        long userId = data.getUserId();
                        CrossUnionActivityRankDataProto.CrossUnionMemberPosDataMsg posDataMsg = null;
                        for (CrossUnionActivityRankDataProto.CrossUnionMemberPosDataMsg tmpMsg : msg.getPosListList()) {
                            if (tmpMsg.getUserId() == userId) {
                                posDataMsg = tmpMsg;
                                break;
                            }
                        }
                        if (posDataMsg == null) {
                            continue;
                        }
                        if (data.isGetReward()) {
                            continue;
                        }
                        data.setGetReward(true);
                        int rank = msg.getRank();
                        ActivityConditionInfo conditionInfo = getUserRankCondition(conditionType, rank);
                        if (conditionInfo != null && updateConditionData(data)) {
                            String rewardStr;
                            if (posDataMsg.getPos() == eUnionPosition.Master.getValue()) {
                                rewardStr = conditionInfo.getMasterRewardStr();
                            } else {
                                //根据职位获取奖励
                                rewardStr = UnionActivityMgr.getUnionMemberPositionDataReward(posDataMsg.getPos(), conditionInfo, userId);
                            }
                            CrossUnionMgr.getRewardHonourItem(rewardStr, activityInfo,rank,msg.getUnionId(),userId);
                            rewardStr = CrossUnionMgr.removeHonourItem(rewardStr);
                            AutoSendActivity.getLogger().info("autoSend unionReward, user: {}, activity: {},conditionType: {}, rank: {}, reward: {}", userId, activityInfo.getActivityId(), conditionType, rank, rewardStr);
                            sendMailReward(userId, rewardStr);
                        }
                    }
                }
            }
        }
        AutoSendActivity.changeSendState(activityInfo.getActivityId(), 2, 1);
    }

    /**
     * 发送成就奖励
     */
    public abstract void sendConditionReward();

    /**
     * 获取需要自动补发的玩家condition
     *
     * @return
     */
    public abstract List<UserActivityConditionData> getNeedSendUserActivityConditionData();

    /**
     * 获取商会condition
     *
     * @return
     */
    public abstract Map<String, UnionActivityConditionData> getUnionActivityConditionData(int conditionType);

    public abstract Map<Long, UserActivityConditionData> getUserActivityRankConditionData(int activityId, int conditionType);

    /**
     * 获取活动配置的所有condition
     *
     * @return
     */
    public Map<Integer, List<ActivityConditionInfo>> getActivityConditionInfo() {
        Map<Integer, Map<Integer, List<ActivityConditionInfo>>> activityConditionInfoTypeMap = new HashMap<>();
        Map<Integer, List<ActivityConditionInfo>> activityConditionInfoMap = new HashMap<>();

        // 跨地区活动
        if (ActivityHelper.isCrossChannelActivityType(activityInfo.getType())) {
            return NormalActivityMgr.getActivityConditionInfoMap(activityInfo.getActivityId());
        }

        // 非跨地区活动
        List<Integer> activityList = Collections.singletonList(activityInfo.getActivityId());
        ActivityBussiness.getActivityConditionInfoMap(activityConditionInfoTypeMap, activityConditionInfoMap, activityList);
        Map<Integer, List<ActivityConditionInfo>> conditionMap = activityConditionInfoTypeMap.get(activityInfo.getActivityId());
        if (conditionMap != null) {
            return conditionMap;
        }
        return new HashMap<>();
    }

    protected void sendMailReward(long userId, String reward) {
        UserInfo userInfo = UserMgr.getUserInfo(userId);
        String language = userInfo.getLanguage();
        String activityName = ActivityMgr.getActivityName(activityInfo, language);
        String mailTitle = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.AUTO_SEND_ACTIVITY_CROSS_RANK_REWARD_TITLE, language), activityName);
        String mailContent = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.AUTO_SEND_ACTIVITY_CROSS_RANK_REWARD_CONTENT, language), activityName);

        //称号奖励，直接生效
        // reward = ActivityMgr.dealWithMailDecorationReward(this.activityInfo.getType(), userId, reward, eLogMoneyType.Mail, eLogMoneyType.MailOpen);

        MailManager.sendMail(userId, eMailType.SYSTEM.getValue(), reward, mailContent, mailTitle,activityInfo.getActivityId(), activityInfo.getServerListStr());
    }

    public ActivityConditionInfo getUserRankCondition(int conditionType, int rank) {
        List<ActivityConditionInfo> infoList = conditionInfoMap.get(conditionType);
        if (null != infoList) {
            for (ActivityConditionInfo conditionInfo : infoList) {
                if (rank >= conditionInfo.getParamList().get(0).intValue() && rank <= conditionInfo.getParamList().get(1).intValue()) {
                    return conditionInfo;
                }
            }
        }
        return null;
    }

    public Map<Long, UserActivityConditionData> getUserNormalActivityRankConditionData(int activityId, int conditionType) {
        List<UserActivityConditionData> dataList = UserActivityBussiness.getUserActivityConditionDataListByType(activityId, conditionType);
        Map<Long, UserActivityConditionData> conditionDataMap = new HashMap<>();
        for (UserActivityConditionData data : dataList) {
            conditionDataMap.put(data.getUserId(), data);
        }
        return conditionDataMap;
    }

    /**
     * 商会分组活动 个人榜 自动发奖
     */
    public void noticeCrossUserYRank(List<String> typeList) {
        if (!UnionActivityGroupHelper.isGroupActivityType(activityInfo.getType())) {
            throw new RuntimeException("看下是不是调用错方法了");
        }

        Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
        if (groupMap != null) {
            for (int groupId : groupMap.keySet()) {
                for (String idKey : typeList) {
                    YRankProto.YRankReqMsg.Builder builder = YRankProto.YRankReqMsg.newBuilder();
                    builder.setActivityId(activityInfo.getActivityId());
                    builder.setGroupId(groupId);
                    builder.setIdKey(idKey);
                    GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C2_CROSS_YRANK_AUTO_SEND_USER_RANK, builder, 0, activityInfo.getActivityId(), groupId);
                }
            }
        }
    }

    /**
     * 商会分组活动 个人榜 自动发奖
     */
    public void noticeCrossUnionYRank(List<String> typeList) {
        if (!UnionActivityGroupHelper.isGroupActivityType(activityInfo.getType())) {
            throw new RuntimeException("看下是不是调用错方法了");
        }

        Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
        if (groupMap != null) {
            for (int groupId : groupMap.keySet()) {
                for (String idKey : typeList) {
                    YRankProto.YRankReqMsg.Builder builder = YRankProto.YRankReqMsg.newBuilder();
                    builder.setActivityId(activityInfo.getActivityId());
                    builder.setGroupId(groupId);
                    builder.setIdKey(idKey);
                    GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C2_CROSS_YRANK_AUTO_SEND_UNION_RANK, builder, 0, activityInfo.getActivityId(), groupId);
                }
            }
        }
    }

    /**
     * 对分组内的活动跨服请求一次,不在YRank里的商会榜单,并且走原有逻辑的商会榜单补发走这个
     */
    public void noticeCrossUserRankByCrossServer() {
        Map<Integer, Integer> crossServerGroupMap = new HashMap<>();
        Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
        if (groupMap != null) {
            for (UnionActivityGroup unionActivityGroup : groupMap.values()) {
                crossServerGroupMap.put(unionActivityGroup.getCrossServerId(), unionActivityGroup.getGroupId());
            }
        }
        if (!crossServerGroupMap.isEmpty()) {
            for (Integer groupId : crossServerGroupMap.values()) {
                AutoSendRewardProto.NoticeCrossUserRankMsg.Builder builder = AutoSendRewardProto.NoticeCrossUserRankMsg.newBuilder();
                builder.setActivityId(activityInfo.getActivityId());
                builder.setActivityType(activityInfo.getType());
                builder.setChildType(activityInfo.getChildType());
                GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_AUTO_SEND_USER_GROUP_RANK_LIST, builder, 0, activityInfo.getActivityId(), groupId);
            }
        }
    }

    /**
     * 对分组内的活动跨服请求一次,不在YRank里的商会榜单,并且走原有逻辑的商会榜单补发走这个
     */
    public void noticeCrossUnionRankByCrossServer() {
        Map<Integer, Integer> crossServerGroupMap = new HashMap<>();
        Map<Integer, UnionActivityGroup> groupMap = GameUnionActivityGroupMgr.getGroupMap(activityInfo.getActivityId());
        if (groupMap != null) {
            for (UnionActivityGroup unionActivityGroup : groupMap.values()) {
                crossServerGroupMap.put(unionActivityGroup.getCrossServerId(), unionActivityGroup.getGroupId());
            }
        }
        if (!crossServerGroupMap.isEmpty()) {
            for (Integer groupId : crossServerGroupMap.values()) {
                AutoSendRewardProto.NoticeCrossUserRankMsg.Builder builder = AutoSendRewardProto.NoticeCrossUserRankMsg.newBuilder();
                builder.setActivityId(activityInfo.getActivityId());
                builder.setActivityType(activityInfo.getType());
                builder.setChildType(activityInfo.getChildType());
                GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C_CROSS_AUTO_SEND_UNION_GROUP_RANK_LIST, builder, 0, activityInfo.getActivityId(), groupId);
            }
        }
    }

}
